<style lang="less">
	.payment{
		.adduser{
			font-weight: bold;
			span{padding-right: 5px;}
		}
		.addinfo{
			font-size: 12px;
		}

		.carbox{
            position: relative;
            background: #fff;
            padding:5px 10px;
            padding-left: 90px;
            height: 90px;
            .img{
                width :70px; height:90px; display: block;
                position: absolute;
                left:10px; top:5px;
            }
            .title{
                 font-size:14px; color:#606266;
            }
            .spec{
                font-size: 12px; color: #909399;
            }
            .price{
                position: absolute;
                bottom: 3px; right:10px;
                font-size: 12px; color:#F56C6C;
				font-family: Arial;
				text-align: right;
                i{
                    font-size: 16px;
                    font-style: normal;
				}
            }
        }
	}
</style>
<template>
    <div class="payment" v-loading="loading">
        <div v-if="defaultaddress.username" @click="$router.push({name:'shop_address'})" class="van-cell van-cell--center van-cell--borderless van-contact-card van-contact-card--edit">
			<i class="van-icon van-icon-contact van-cell__left-icon"></i>
			<div class="van-cell__value van-cell__value--alone">
				<div class="adduser">
					<span>{{defaultaddress.username}}</span>
					<span>{{defaultaddress.mobile}}</span>
				</div>
				<div class="addinfo">{{defaultaddress.regions_name+' '+defaultaddress.address}}</div>
			</div>
			<i class="van-icon van-icon-arrow van-cell__right-icon"></i>
		</div>
		<div v-else @click="$router.push({name:'shop_address'})" class="van-cell van-cell--center van-cell--borderless van-cell--clickable van-contact-card van-contact-card--add">
			<i class="van-icon van-icon-add2 van-cell__left-icon"></i>
			<div class="van-cell__value van-cell__value--alone">选择收货地址</div>
			<i class="van-icon van-icon-arrow van-cell__right-icon"></i>
		</div>
		<h5 class="__title">商品信息</h5>
		<div style="background:#fff;padding:5px 0;">
			<div class="carbox" v-for="(item,key) in data" :key="item.buyer_id+key">
				<div style="height:100%;">
					<img class="img" :src="imgurl(item.item)">
					<p class="title">{{item.item.goods.title}}</p>
					<p class="spec">
						<span v-for="(value,key) in item.item.spec_data" :key="key">
							{{key}} : {{value}}
						</span>
					</p>
					<span class="price">
						<p style="color:#909399;">X <i>{{item.count}}</i></p>
						<p>￥<i>{{item.item.price}}</i></p>
					</span>
				</div>
			</div>
		</div>
		<div style="height:15px;"></div>
		<van-cell-group>
			<van-cell title="运费" :value="'￥'+calculate"/>
			<van-cell title="优惠券" v-if="coupondata.length" :value="coupontext" is-link @click="couponpop = true" />
			<van-cell title="优惠券" v-else value="暂无可用优惠券"/>
			<van-cell title="发票" is-link :value="invoice" @click="invoicepop = true" />
		</van-cell-group>
		<van-submit-bar :price="(sum_price - discount_price) *100" button-text="提交订单" @submit="onSubmit"/>
		<van-popup v-model="couponpop" position="bottom" style="height:60%">
			<h4 class="__title">选择优惠券</h4>
			<div class="van-coupon-list__list">
				<div class="van-coupon-item" v-for="coupon in coupondata" :key="coupon.id" @click="changecoupon(coupon)">
					<div class="van-coupon-item__content">
						<div class="van-coupon-item__head">
							<h2 v-if="coupon.face_type == '0'"><span>¥</span>{{Number(coupon.face_value)}}</h2>
							<h2 v-else>{{Number(coupon.face_value)}}折</h2>
							<p>{{instructions(coupon)}}</p>
						</div>
						<div class="van-coupon-item__body">
							<h2>{{coupon.name}}</h2>
							<p v-if="coupon.time_type == '0'">有效期：{{coupon.start_time.substring(0,10)}}至{{coupon.end_time.substring(0,10)}}</p>
							<p v-else-if="coupon.time_type == '1'">有效期：自领卡之日起{{coupon.valid_day}}天有效</p>
							<p v-else>有效期：永久有效</p>
							<div class="van-checkbox van-coupon-item__corner" v-if="changecouponid == coupon.id">
								<div class="van-checkbox__icon van-checkbox__icon--round van-checkbox__icon--checked">
									<i class="van-icon van-icon-success"></i>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</van-popup>
		<van-dialog v-model="invoicepop" show-cancel-button>
			<h4 class="__title">发票title信息</h4>
			<van-field
				v-model="invoice"
				label="单位名称"
				placeholder="请输入单位名称"
			/>
			<div style="padding:10px 15px;">
				<p style="font-size:12px; color:#909399;">发票内容：购买商品明细!</p>
				<p style="font-size:12px; color:#909399;">发票抬头：请确认单位名称正确,以免因名称错误耽搁您的报销。!</p>
			</div>
		</van-dialog>
	</div>
</template>

<script>
    import { mapState,mapActions } from 'vuex';
    import axios from 'axios';
	import cookie from 'js-cookie';
  	const Base64 = require('js-base64').Base64;
    export default {
        name: "cart",
        data() {
            return {
              calculate : 0, //运费
              invoice : '',//发票title信息
              invoicepop : false,
              tanantId : cookie.get('tanantId'),
              coupondata : [], //优惠券
              couponpop : false, //优惠券弹出层
              changecouponid : 0, //选中优惠券id
            }
        },
        methods: {
			instructions(coupons){
				let text = '';
				if(coupons.is_original_price == 1){
					text += '仅原价购买使用、';
				}
				if(coupons.doorsill != 0){
					// text += '满'+coupons.doorsill+'元使用、';
				}
				if(coupons.goods){
					text += '指定商品使用、';
				}
				if(coupons.store){
					text += '指定店仓使用';
				}
				if(text == ''){
					return '';
				}
				return '使用限制：'+text;
			},
			imgurl (data){
				if(data.goods.images != ''){
					return this.$http.IMGURL + data.goods.images;
				}else if(data.images != ''){
					return this.$http.IMGURL + data.images;
				}else{
					return 'http://res2.esf.leju.com/esf_www/statics/images/default-img/detail.png';
				}
			},
			//获取优惠券
			getcoupon(){
				this.$http.member.post('coupon/valid',{
					vip_id : this.$store.state.user.userindex.data.id,
					store_id : this.store_id,
					is_original_price : this.is_original_price,
					goods : this.data.map(item => {
						return {
							sku_id : item.item_id, //商品id
							// pay_money : (item.item.price * item.count * (item.discount / 10)).toFixed(2)
							pay_money : (item.item.price * item.count).toFixed(2)
						}
					})
				}).then(res => {
					if(!res.data.code){
						//设置优惠券数据
						this.coupondata = res.data.data;
					}
				},res => {
					console.log(res)
				})
			},
			changecoupon(coupon){
				this.changecouponid = coupon.id;
				this.couponpop = false;
			},
			//获取运费
			getcalculate(){
				this.calculate = 0;
				this.$http.setting.post('dispatch/'+this.tanantId+'/calculate',{
					goods_weight: "0",   //总重量
					goods_num: this.sum_count,  //总数量
					take_area: this.take_area //邮寄区域 市级名称
				}).then(res => {
					if(!res.data.code){
						this.calculate = res.data.data.dispatch_fee;
					}
				}).catch(err => {
				  this.$toast.fail(err.message);
        })
			},
			onSubmit(){
        // var goods = this.data;
        // var itemId='';
        // var newData = [];
        // for(var j = 0;j<goods.length;j++){
        //   itemId = goods.item_id
        //   if(j!=0){
        //     if(itemId.item_id!=goods[h].item_id){
        //       newData.push(goods[h])
        //     }else{
        //
        //     }
        //   }
        //
        // }
        // console.log(newData)
				this.$http.order.post('shop/order',{
					store_id : this.store_id,//店仓id
					address_id : this.defaultaddress.id,
					address : Base64.encode(JSON.stringify(this.defaultaddress)),//base64加密地址对象
					coupon_id : this.coupon_id,//优惠券id
					price : this.sum_price,// 订单总金额(总价-折后价)
					goods_price : this.sum_price - this.calculate,//商品总金额(订单总金额-运费)
					discount_price : this.discount_price,//优惠总金额
					freight_type : "0",//运费类型  。0固定运费，1运费模版
					freight_fee : this.calculate,	//运费
					freight_template_id : "0", //运费模版id(没有填0)
					invoice : this.invoice, //发票抬头信息
					buynow : this.$store.state.shop.buynow,	//是否立即购买，0，表示从购物车点击结算
					items : this.data.map(item => {
						return {
							item_id: item.item_id,
							code: item.item.code,
							numero: item.item.numero,
							price: item.item.price,
							supplier_tid: item.item.supplier_tid,
							supplier_id: item.item.supplier_id,
							goods_id: item.item.goods_id,
							goods: {
								sn: item.item.sn
							},
							real_price: item.item.price*item.count,
							total: item.count
						}
					})
				}).then(res => {
					if(!res.data.code){
						this.$router.push({name:'shop_pay',params:{id:res.data.data.id}})
					}else{
            this.$toast.fail(res.data.message);
          }
				})
			}
        },
        computed: {
            loading(){
                return this.$store.state.shop.addressloading;
            },
            data(){
				if(this.$store.state.shop.buynow == 0){
					return this.$store.state.shop.cardata.filter(i => i.checked);
				}else{
					let paymentdata = this.$store.state.shop.paymentdata;
					if(!paymentdata.length) this.$router.push({name:'shop_card'})
					return paymentdata;
				}
			},
			defaultaddress(){
				return this.$store.getters['shop/defaultaddress'];
			},
            sum_price(){
                let a = 0;
                this.data.map(item => {
                    a += item.count * item.item.price
                })
                return a;
			},
			sum_count(){
                let a = 0;
                this.data.map(item => {
                    a += item.count
                })
                return a;
			},
			take_area(){
				if(!this.defaultaddress.regions_name) return '';
				return this.defaultaddress.regions_name.split('-')[1]
			},
			//店仓id 取第一个商品的店仓id
			store_id(){
				if(this.data.length){
					return this.data[0].store_id
				}
				return 0;
			},
			//优惠总金额
			discount_price(){
				let a = 0;
				if(this.changecouponid){
					if(this.changecoupondata.face_type == '0'){
						a = Number(this.changecoupondata.face_value)
					}else{
						a = this.sum_price * (10 - Number(this.changecoupondata.face_value)) / 10
					}
				}
				return a
			},
			//商品是否为原价商品 全部
			is_original_price(){
				return true
			},
			changecoupondata(){
				let coupon = this.coupondata.filter(f => f.id == this.changecouponid);
				if(coupon.length){
					return coupon[0]
				}else{
					return {}
				}
			},
			coupontext(){
				if(this.changecouponid){
					let a = this.changecoupondata.face_type == '0' ? '￥'+Number(this.changecoupondata.face_value) : Number(this.changecoupondata.face_value)+'折'
					return '已选择"'+this.changecoupondata.name+'"('+a+')'
				}else{
					return '您有'+this.coupondata.length+'张优惠券可用'
				}
			}
        },
        mounted(){

        },
        created(){
			this.$store.dispatch('shop/initaddress');
			// this.getcoupon();
		},
		watch : {
			data : {
				handler(value) {
					if(!value.length){
						this.$router.push({name:'shop_card'})
					}
				},
				immediate: true
			},
        defaultaddress : {
          handler(value) {
            if(value.regions_name){
              this.getcalculate();
            }
          },
          immediate: true,
          deep: true,
        }
		  },
      mounted() {

      }
    }
</script>

